/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mailclient;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Vector;
import javax.mail.internet.InternetAddress;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import pojo.ThongTinKey;
import dao.*;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Calendar;
import javax.crypto.spec.SecretKeySpec;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import sun.security.util.PropertyExpander;

/**
 *
 * @author DQ
 */
public class ManageKey extends javax.swing.JFrame {

    private final DefaultTableModel tableModel;
    private int maKeyDuocChon = -1;

    /**
     * Creates new form ManageKey
     */
    public ManageKey() {
        initComponents();
        buttonGroup2.add(jrdb_PriKeyEdit);
        buttonGroup2.add(jrdb_PreSharedEdit);
        buttonGroup2.add(jrdb_PubKeyEdit);
        buttonGroup1.add(jrdb_PreSharedAdd);
        buttonGroup1.add(jrdb_PriKeyAdd);
        buttonGroup1.add(jrdb_PubKeyAdd);

        jrdb_PreSharedAdd.setSelected(true);
        jrdb_PreSharedEdit.setSelected(true);
        this.tableModel = new DefaultTableModel();
        this.tableModel.addColumn("Mã Key  ");
        this.tableModel.addColumn("Loại Key  ");

        this.tableModel.addColumn("Địa chỉ Mail ");
        this.tableModel.addColumn("Đường dẫn file ");
        this.jtb_DanhSachKey.setModel(tableModel);
        TableColumn column = this.jtb_DanhSachKey.getColumnModel().getColumn(0);
        column.setPreferredWidth(50);
        column = this.jtb_DanhSachKey.getColumnModel().getColumn(1);
        column.setPreferredWidth(50);
        column = this.jtb_DanhSachKey.getColumnModel().getColumn(2);
        column.setPreferredWidth(200);
        column = this.jtb_DanhSachKey.getColumnModel().getColumn(3);
        column.setPreferredWidth(400);


        this.HienThiDanhSachKey();

    }

    private void HienThiDanhSachKey() {
        try {
            for (int i = this.tableModel.getRowCount(); i > 0; i--) {
                this.tableModel.removeRow(i - 1);
            }
            ArrayList<ThongTinKey> arrTTK = new ArrayList<>();
            arrTTK = ThongTinKeyDAO.layTatCaThongTinKey();
            for (int i = 0; i < arrTTK.size(); i++) {
                ThongTinKey ttk = arrTTK.get(i);
                Vector vt = new Vector();

                vt.add(Integer.toString(ttk.getMaKey()));
                vt.add(ttk.getLoaiKey());
                vt.add(ttk.getDiaChiMail());
                vt.add(ttk.getDuongDan());

                this.tableModel.addRow(vt);
            }
        } catch (Exception ex) {
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        buttonGroup2 = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtb_DanhSachKey = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jtf_KeyCuaAdd = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jbtn_ThemKey = new javax.swing.JButton();
        jrdb_PubKeyAdd = new javax.swing.JRadioButton();
        jrdb_PriKeyAdd = new javax.swing.JRadioButton();
        jLabel6 = new javax.swing.JLabel();
        jtf_DuongDanAdd = new javax.swing.JTextField();
        jbtn_BrowseAdd = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jbtn_GenKeyDoiXung = new javax.swing.JButton();
        jbtn_GenKey = new javax.swing.JButton();
        jrdb_PreSharedAdd = new javax.swing.JRadioButton();
        jbtn_Close = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jbtn_XoaKey = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jbtn_BrowseEdit = new javax.swing.JButton();
        jtf_KeyCuaEdit = new javax.swing.JTextField();
        jtf_DuongDanEdit = new javax.swing.JTextField();
        jrdb_PubKeyEdit = new javax.swing.JRadioButton();
        jrdb_PriKeyEdit = new javax.swing.JRadioButton();
        jbtn_CapNhat = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jrdb_PreSharedEdit = new javax.swing.JRadioButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Quản Lý Thông Tin Key");

        jtb_DanhSachKey.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jtb_DanhSachKey.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtb_DanhSachKeyMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtb_DanhSachKey);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Thêm Key "));

        jtf_KeyCuaAdd.setToolTipText("");

        jLabel2.setText("Email :");

        jLabel3.setText("Ex : abc@gmail.com");

        jbtn_ThemKey.setText("Thêm Key Vào Hệ Thống");
        jbtn_ThemKey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtn_ThemKeyActionPerformed(evt);
            }
        });

        jrdb_PubKeyAdd.setText("Public Key");
        jrdb_PubKeyAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrdb_PubKeyAddActionPerformed(evt);
            }
        });

        jrdb_PriKeyAdd.setText("Private Key");
        jrdb_PriKeyAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrdb_PriKeyAddActionPerformed(evt);
            }
        });

        jLabel6.setText("Đường dẫn : ");

        jbtn_BrowseAdd.setText("Chọn File ...");
        jbtn_BrowseAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtn_BrowseAddActionPerformed(evt);
            }
        });

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Khởi Tạo Key "));

        jbtn_GenKeyDoiXung.setText("Khởi Tạo Key Đối Xứng");
        jbtn_GenKeyDoiXung.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtn_GenKeyDoiXungActionPerformed(evt);
            }
        });

        jbtn_GenKey.setText("Khởi Tạo Key Bất Đối Xứng");
        jbtn_GenKey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtn_GenKeyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jbtn_GenKeyDoiXung, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 55, Short.MAX_VALUE)
                .addComponent(jbtn_GenKey))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addGap(0, 11, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtn_GenKeyDoiXung)
                    .addComponent(jbtn_GenKey)))
        );

        jrdb_PreSharedAdd.setText("Key Đối Xứng");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtf_KeyCuaAdd))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtf_DuongDanAdd))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addComponent(jrdb_PreSharedAdd)
                                .addGap(18, 18, 18)
                                .addComponent(jrdb_PubKeyAdd)
                                .addGap(18, 18, 18)
                                .addComponent(jrdb_PriKeyAdd)
                                .addGap(4, 4, 4)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jbtn_BrowseAdd)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGap(0, 2, Short.MAX_VALUE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jbtn_ThemKey, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jtf_KeyCuaAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jtf_DuongDanAdd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtn_BrowseAdd))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jrdb_PubKeyAdd)
                    .addComponent(jrdb_PriKeyAdd)
                    .addComponent(jrdb_PreSharedAdd))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtn_ThemKey)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbtn_Close.setText("Thoát");
        jbtn_Close.setToolTipText("");
        jbtn_Close.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtn_CloseActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Cập nhật thông tin Key"));
        jPanel1.setToolTipText("");

        jbtn_XoaKey.setText("Xóa Key");
        jbtn_XoaKey.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtn_XoaKeyActionPerformed(evt);
            }
        });

        jLabel4.setText("Email : ");

        jLabel5.setText("Đường dẫn : ");

        jbtn_BrowseEdit.setText("Chọn File ...");
        jbtn_BrowseEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtn_BrowseEditActionPerformed(evt);
            }
        });

        jrdb_PubKeyEdit.setText("Public Key");

        jrdb_PriKeyEdit.setText("Private Key");
        jrdb_PriKeyEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrdb_PriKeyEditActionPerformed(evt);
            }
        });

        jbtn_CapNhat.setText("Cập Nhật Key");
        jbtn_CapNhat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtn_CapNhatActionPerformed(evt);
            }
        });

        jLabel7.setText("Ex : abc@gmail.com");

        jrdb_PreSharedEdit.setText("Key Đối Xứng");
        jrdb_PreSharedEdit.setToolTipText("");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jLabel4)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtf_KeyCuaEdit))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(29, 29, 29)
                                .addComponent(jtf_DuongDanEdit))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(0, 21, Short.MAX_VALUE)
                                .addComponent(jrdb_PreSharedEdit)
                                .addGap(18, 18, 18)
                                .addComponent(jrdb_PubKeyEdit)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jrdb_PriKeyEdit)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jbtn_BrowseEdit)
                            .addComponent(jLabel7)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jbtn_XoaKey)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jbtn_CapNhat)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jtf_KeyCuaEdit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jbtn_BrowseEdit)
                    .addComponent(jtf_DuongDanEdit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jrdb_PubKeyEdit)
                    .addComponent(jrdb_PriKeyEdit)
                    .addComponent(jrdb_PreSharedEdit))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtn_CapNhat)
                    .addComponent(jbtn_XoaKey))
                .addGap(88, 88, 88))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jbtn_Close)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 0, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(jbtn_Close)
                .addContainerGap())
        );

        jbtn_Close.getAccessibleContext().setAccessibleName("Close");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtn_CloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtn_CloseActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);

    }//GEN-LAST:event_jbtn_CloseActionPerformed

    private void jbtn_GenKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtn_GenKeyActionPerformed
        // TODO add your handling code here:
        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
            kpg.initialize(1024);
            KeyPair kp = kpg.genKeyPair();

            final JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = fc.showOpenDialog(this);
            if (returnVal == 0) {
                String path = fc.getSelectedFile().getAbsolutePath();

                SaveKeyPair(path, kp);

                JFrame frame = new JFrame("Show Message Dialog");
                JOptionPane.showMessageDialog(frame, "Phát sinh và lưu key thành công !");
            }


        } catch (Exception ex) {
            JFrame frame = new JFrame("Show Message Dialog");
            JOptionPane.showMessageDialog(frame, "Đã có lỗi trong lúc phát sinh và lưu key !");
        }

    }//GEN-LAST:event_jbtn_GenKeyActionPerformed

    class MyFilter extends javax.swing.filechooser.FileFilter {

        @Override
        public boolean accept(File file) {
            String filename = file.getName();
            return filename.endsWith(".key");
        }

        @Override
        public String getDescription() {
            return "*.key";
        }
    }

    private void jbtn_BrowseAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtn_BrowseAddActionPerformed
        // TODO add your handling code here:
        try {
            final JFileChooser fc = new JFileChooser();

            //fc.setFileFilter(new MyFilter());
            int returnVal = fc.showOpenDialog(this);
            if (returnVal == 0) {
                String path = fc.getSelectedFile().getAbsolutePath();
                jtf_DuongDanAdd.setText(path);
            }

        } catch (Exception ex) {
            JFrame frame = new JFrame("Show Message Dialog");
            JOptionPane.showMessageDialog(frame, "Đã có lỗi trong lúc mở file Key !");
        }


    }//GEN-LAST:event_jbtn_BrowseAddActionPerformed

    private void jbtn_ThemKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtn_ThemKeyActionPerformed
        // TODO add your handling code here:
        try {
            ThongTinKey ttk = new ThongTinKey();
            ThongTinKey ttkOld = new ThongTinKey();
            ttk.setDiaChiMail(jtf_KeyCuaAdd.getText());
            ttk.setDuongDan(jtf_DuongDanAdd.getText());
            if (jrdb_PriKeyAdd.isSelected()) {
                ttk.setLoaiKey("Private");
                ttkOld = ThongTinKeyDAO.timKiemPrivateKey(ttk.getDiaChiMail());
            } else {
                if (jrdb_PubKeyAdd.isSelected()) {
                    ttk.setLoaiKey("Public");
                    ttkOld = ThongTinKeyDAO.timKiemPublicKey(ttk.getDiaChiMail());
                } else {
                    ttk.setLoaiKey("PreShared");
                    ttkOld = ThongTinKeyDAO.timKiemPreSharedKey(ttk.getDiaChiMail());
                }

            }

            if (ttkOld == null) {
                ttk.setMaKey(ThongTinKeyDAO.layMaKeyTuFile());
                ThongTinKeyDAO.themKeyMoi(ttk);
                JFrame frame = new JFrame("Show Message Dialog");
                JOptionPane.showMessageDialog(frame, "Thêm Key vào hệ thống thành công !");
                this.HienThiDanhSachKey();
            } else {
                JFrame frame = new JFrame("Show Message Dialog");
                JOptionPane.showMessageDialog(frame, "Key này đã tồn tại trong hệ thống, Vui lòng kiểm tra lại !");
            }


        } catch (Exception ex) {
            JFrame frame = new JFrame("Show Message Dialog");
            JOptionPane.showMessageDialog(frame, "Đã có lỗi trong lúc thêm Key vào hệ thống !");
        }
    }//GEN-LAST:event_jbtn_ThemKeyActionPerformed

    private void jtb_DanhSachKeyMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtb_DanhSachKeyMouseClicked
        // TODO add your handling code here:
        int dong = this.jtb_DanhSachKey.getSelectedRow();
        this.jtf_DuongDanEdit.setText(this.jtb_DanhSachKey.getValueAt(dong, 3).toString());
        this.jtf_KeyCuaEdit.setText(this.jtb_DanhSachKey.getValueAt(dong, 2).toString());
        String LoaiKey = this.jtb_DanhSachKey.getValueAt(dong, 1).toString();
        if (LoaiKey.equals("Public")) {
            jrdb_PubKeyEdit.setSelected(true);
        } else {
            if (LoaiKey.equals("Private")) {
                jrdb_PriKeyEdit.setSelected(true);
            } else {
                jrdb_PreSharedEdit.setSelected(true);
            }

        }
        this.maKeyDuocChon = Integer.parseInt(this.jtb_DanhSachKey.getValueAt(dong, 0).toString());
    }//GEN-LAST:event_jtb_DanhSachKeyMouseClicked

    private void jbtn_CapNhatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtn_CapNhatActionPerformed
        // TODO add your handling code here:
        try {
            ThongTinKey ttk = new ThongTinKey();
            ThongTinKey ttkOld = new ThongTinKey();
            ttk.setMaKey(this.maKeyDuocChon);
            ttk.setDuongDan(this.jtf_DuongDanEdit.getText());
            ttk.setDiaChiMail(this.jtf_KeyCuaEdit.getText());


            if (jrdb_PubKeyEdit.isSelected()) {
                ttk.setLoaiKey("Public");
                ttkOld = ThongTinKeyDAO.timKiemPrivateKey(ttk.getDiaChiMail());
            } else {
                if (jrdb_PriKeyEdit.isSelected()) {
                    ttk.setLoaiKey("Private");
                    ttkOld = ThongTinKeyDAO.timKiemPrivateKey(ttk.getDiaChiMail());
                } else {
                    ttk.setLoaiKey("PreShared");
                    ttkOld = ThongTinKeyDAO.timKiemPreSharedKey(ttk.getDiaChiMail());
                }

            }
            if (ttkOld == null) {
                ThongTinKeyDAO.capNhatThongTinKey(ttk);
                JFrame frame = new JFrame("Show Message Dialog");
                JOptionPane.showMessageDialog(frame, "Cập nhật Key vào hệ thống thành công !");
                HienThiDanhSachKey();

            } else {
                JFrame frame = new JFrame("Show Message Dialog");
                JOptionPane.showMessageDialog(frame, "Key này đã tồn tại trong hệ thống, Vui lòng kiểm tra lại !");
            }

        } catch (Exception ex) {
            JFrame frame = new JFrame("Show Message Dialog");
            JOptionPane.showMessageDialog(frame, "Đã có lỗi khi cập nhật Key vào hệ thống !");
        }

    }//GEN-LAST:event_jbtn_CapNhatActionPerformed

    private void jbtn_XoaKeyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtn_XoaKeyActionPerformed
        // TODO add your handling code here:
        try {
            ThongTinKey ttk = new ThongTinKey();
            ttk.setMaKey(this.maKeyDuocChon);
            JFrame frame = new JFrame("Show Message Dialog");
            int returnVal = JOptionPane.showConfirmDialog(frame, "Bạn muốn Xóa Key ra khỏi hệ thống ?");
            if (returnVal == 0) {
                ThongTinKeyDAO.xoaThongTinKey(ttk);
                JFrame fr = new JFrame("Show Message Dialog");
                JOptionPane.showMessageDialog(fr, "Xóa Key ra khỏi hệ thống thành công !");
                HienThiDanhSachKey();
            }


        } catch (Exception ex) {
            JFrame frame = new JFrame("Show Message Dialog");
            JOptionPane.showMessageDialog(frame, "Đã có lỗi khi xóa Key ra khỏi hệ thống !");
        }


    }//GEN-LAST:event_jbtn_XoaKeyActionPerformed

    private void jbtn_BrowseEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtn_BrowseEditActionPerformed
        // TODO add your handling code here:
        try {
            final JFileChooser fc = new JFileChooser();

            //fc.setFileFilter(new MyFilter());
            int returnVal = fc.showOpenDialog(this);
            if (returnVal == 0) {
                String path = fc.getSelectedFile().getAbsolutePath();
                jtf_DuongDanEdit.setText(path);
            }

        } catch (Exception ex) {
            JFrame frame = new JFrame("Show Message Dialog");
            JOptionPane.showMessageDialog(frame, "Đã có lỗi trong lúc mở file Key !");
        }

    }//GEN-LAST:event_jbtn_BrowseEditActionPerformed
    private static Key generateKey() throws Exception {
        Calendar currentDate = Calendar.getInstance();
        SimpleDateFormat formatter =
                new SimpleDateFormat("yy/MM/ddHH:mm:ss");
        String test = formatter.format(currentDate.getTime());

        byte[] b = new byte[test.length()];
        for (int i = 0; i < test.length(); i++) {
            char temp = test.charAt(i);
            b[i] = (byte) temp;
        }
        Key key = new SecretKeySpec(b, "AES");
        return key;
    }
    private void jbtn_GenKeyDoiXungActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtn_GenKeyDoiXungActionPerformed
        // TODO add your handling code here:
        try {
            Key key = generateKey();
            final JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            int returnVal = fc.showOpenDialog(this);

            if (returnVal == 0) {
                String path = fc.getSelectedFile().getAbsolutePath();
                SavePreSharedKey(path, key);
            }

        } catch (Exception ex) {
            JFrame frame = new JFrame("Show Message Dialog");
            JOptionPane.showMessageDialog(frame, "Đã có lỗi trong lúc khởi tạo Key !");
        }
    }//GEN-LAST:event_jbtn_GenKeyDoiXungActionPerformed

    private void jrdb_PriKeyAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrdb_PriKeyAddActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jrdb_PriKeyAddActionPerformed

    private void jrdb_PubKeyAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrdb_PubKeyAddActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jrdb_PubKeyAddActionPerformed

    private void jrdb_PriKeyEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrdb_PriKeyEditActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jrdb_PriKeyEditActionPerformed

    public void SavePreSharedKey(String path, Key key) {
        try {
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
                    key.getEncoded());
            FileOutputStream fos = new FileOutputStream(path + "/PreShared.key");
            fos.write(x509EncodedKeySpec.getEncoded());
            fos.close();
        } catch (Exception ex) {
        }
    }

    public void SaveKeyPair(String path, KeyPair keyPair) throws IOException {
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();

// Store Public Key.
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
                publicKey.getEncoded());
        FileOutputStream fos = new FileOutputStream(path + "/public.key");
        fos.write(x509EncodedKeySpec.getEncoded());
        fos.close();

// Store Private Key.
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
                privateKey.getEncoded());
        fos = new FileOutputStream(path + "/private.key");
        fos.write(pkcs8EncodedKeySpec.getEncoded());
        fos.close();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ManageKey.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ManageKey.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ManageKey.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ManageKey.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ManageKey().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.ButtonGroup buttonGroup2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtn_BrowseAdd;
    private javax.swing.JButton jbtn_BrowseEdit;
    private javax.swing.JButton jbtn_CapNhat;
    private javax.swing.JButton jbtn_Close;
    private javax.swing.JButton jbtn_GenKey;
    private javax.swing.JButton jbtn_GenKeyDoiXung;
    private javax.swing.JButton jbtn_ThemKey;
    private javax.swing.JButton jbtn_XoaKey;
    private javax.swing.JRadioButton jrdb_PreSharedAdd;
    private javax.swing.JRadioButton jrdb_PreSharedEdit;
    private javax.swing.JRadioButton jrdb_PriKeyAdd;
    private javax.swing.JRadioButton jrdb_PriKeyEdit;
    private javax.swing.JRadioButton jrdb_PubKeyAdd;
    private javax.swing.JRadioButton jrdb_PubKeyEdit;
    private javax.swing.JTable jtb_DanhSachKey;
    private javax.swing.JTextField jtf_DuongDanAdd;
    private javax.swing.JTextField jtf_DuongDanEdit;
    private javax.swing.JTextField jtf_KeyCuaAdd;
    private javax.swing.JTextField jtf_KeyCuaEdit;
    // End of variables declaration//GEN-END:variables
}
